package com.hoshino.momochi.controller;

import com.hoshino.momochi.annotation.IgnoreLogin;
import com.hoshino.momochi.annotation.LimitCount;
import com.hoshino.momochi.model.DTO.MailDTO;
import com.hoshino.momochi.service.MailService;
import com.hoshino.momochi.service.RedisService;
import com.hoshino.momochi.service.UserDetailsService;
import com.hoshino.momochi.service.UserService;
import com.hoshino.momochi.util.CodeEnum;
import com.hoshino.momochi.util.JsonResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;

@RestController
public class MailController {

    @Autowired
    private MailService mailService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    private void doMail(String toPerson) {
        if (Objects.isNull(toPerson)) {
            return;
        }
        String Code = StringUtils.join(ThreadLocalRandom.current().nextInt(100000, 999999)); // 生成验证码
        redisService.addMailToCode(toPerson, Code);
        mailService.sendMail(toPerson, Code);
    }

    /**
     * 请求 发送邮箱 验证码
     *
     * @param request
     * @param mailDTO mail
     * @return
     */
    @RequestMapping("api/mail/requestCode")
    @IgnoreLogin
    @LimitCount(key = "mail", name = "邮箱接口", prefix = "mail", count = 1)
    public JsonResponse requestMailCode(HttpServletRequest request, @RequestBody MailDTO mailDTO) {
        // 请求获取邮箱验证码
        // 相同 IP 地址 在 一定时间内只能请求一次 邮箱验证码
        // 对于 找回密码 or 修改邮箱操作
        // 对于 注册 发送邮箱验证码操作
        Long uid = (Long) request.getAttribute(CodeEnum.USERID.getMessage());
        doMail(userService.getMailByUserId(uid));
        doMail(mailDTO.getMail());
        return JsonResponse.success(CodeEnum.CODESEND.getCode(), CodeEnum.CODESEND.getMessage());
    }
}
